package cn.com.generaldata.os.ws.impl;

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jasig.cas.client.util.CommonUtils;
import org.nutz.dao.QueryResult;
import org.nutz.ioc.annotation.InjectName;
import org.nutz.json.Json;
import org.nutz.lang.Streams;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.common.net.HttpHeaders;

import cn.com.generaldata.jsme_indicator_system.entity.IndicatorInfo;
import cn.com.generaldata.os.result.ReportIndicatorQueryResult;
import cn.com.generaldata.os.result.ReportVerityQueryResult;
import cn.com.generaldata.os.service.impl.IndicatorInfoService;
import cn.com.generaldata.os.service.impl.ReportIndicatorQueryService;
import cn.com.generaldata.os.service.impl.ReportIndicatorQueryService.ReportIndicaotrQueryGrid;
import cn.com.generaldata.os.vo.AreaVO;
import cn.com.generaldata.os.vo.DynamicReportVO;
import cn.com.generaldata.os.vo.ReportIndicatorQueryVO;
import cn.com.generaldata.os.vo.ResultVO;
import edu.emory.mathcs.backport.java.util.Arrays;

@Component
@InjectName
public class IndicatorQueryWS{

	private static final Logger logger = LoggerFactory.getLogger(IndicatorQueryWS.class);

	@Autowired
	private IndicatorInfoService indicatorInfoService;

	@Autowired
	private ReportIndicatorQueryService reportIndicatorQueryService;

	@Autowired
	private AreaWS areaService;
	
	
	@Autowired
	private VersionWS versionService;
	
	@Autowired
	private UnitWS unitService;
	
	//	
	public Map<Integer, String> getStatSystems() {
		return indicatorInfoService.getStatSystems();
	}

	@At("/audit/queryIndicators")
	@Ok("json")
	public ResultVO<IndicatorInfo> queryIndicators(@Param("statSystem") int statSystem,@Param("industryCode") String industryCode,
			@Param("indicatorName") String name,@Param("indicatorCode") String code,@Param("pageNum") int pageNum) {
		QueryResult qr = indicatorInfoService.queryIndicator(statSystem, industryCode, name, code, pageNum);

		ResultVO<IndicatorInfo> r = new ResultVO<IndicatorInfo>();
		r.setOperationResult(qr.getList(IndicatorInfo.class));
		r.setPageNumber(pageNum);
		r.setPageSize(ResultVO.DEFAULT_PAGE_SIZE);
		r.setTotalCount(qr.getPager().getRecordCount());

		return r;
	}

	
	public ReportIndicatorQueryResult queryReportIndicator(ReportIndicatorQueryVO queryVO) {
		ReportIndicatorQueryResult result = new ReportIndicatorQueryResult();
		try {
			ReportIndicaotrQueryGrid grid = reportIndicatorQueryService.queryReportIndicators(queryVO);
			result.setQueryResult(Json.toJson(grid.getBody()));
			result.setHead(grid.getHead());
			return result;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result.setDefaultError();
			return result;
		}

	}

	@At("/audit/queryIndicatorToPage")
	@Ok("jsp:/static/ocean/audit/indicatorFindList")
	public void queryReportIndicatorToPage(HttpServletRequest request) {
		
		request.setAttribute("areasMap", listToMap(areaService.queryAreas()));
		request.setAttribute("versionYearList", versionService.getReportVersionYearRange());
		request.setAttribute("roleList", unitService.queryRoles());	//单位类型
	}
	
	
	@At("/audit/queryIndicator")
	@Ok("json")
	public ReportVerityQueryResult queryReportIndicatorNew(@Param("..") ReportIndicatorQueryVO queryVO, @Param("indicatorListData") String indicatorListData, HttpServletRequest request) {

		if (CommonUtils.isNotBlank(indicatorListData)){			
			String[] param = indicatorListData.split(",");
			List<String> indicators = Arrays.asList(param);
			queryVO.setIndicators(indicators);
		}
		
		
		ReportVerityQueryResult result = new ReportVerityQueryResult();
		try {
			
			if (queryVO.getStartYear()!=null&&queryVO.getEndYear()!=null){
				DynamicReportVO grid = reportIndicatorQueryService.queryReportIndicatorsNew(queryVO,true);
				result.setQueryResult(Json.toJson(grid.getBody()));
				List<List<String>> headers = grid.getHeaders();
				List<String> headList = headers.get(0);
				//			Set headSet = new HashSet(headList);
				//			Set unitSet = new HashSet(unitList);
				result.setHead(headList);
			}			

			return result;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result.setDefaultError();
			return result;
		}

	}
	
	@At("/audit/importIndicatorNew")
	@Ok("void")
	public void importIndicatorNew(@Param("..") ReportIndicatorQueryVO queryVO, @Param("indicatorListData") String indicatorListData, HttpServletRequest request, HttpServletResponse response) {
		
		if (CommonUtils.isNotBlank(indicatorListData)){			
			String[] param = indicatorListData.split(",");
			List<String> indicators = Arrays.asList(param);
			queryVO.setIndicators(indicators);
		}
		

		response.setContentType("multipart/form-data");
		
		OutputStream out = null;
		try {
			
			String fileName = "指标查询结果.xls";
			
			String userAgent = request.getHeader("User-Agent");
			byte[] bytes = userAgent.contains("MSIE") ? fileName.getBytes() : fileName.getBytes("UTF-8"); // fileName.getBytes("UTF-8")处理safari的乱码问题
			fileName = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
			response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName));

			out = response.getOutputStream();
			DynamicReportVO grid = reportIndicatorQueryService.queryReportIndicatorsNew(queryVO,false);
			if (grid.getBody() != null && grid.getBody().size() > 0)
				reportIndicatorQueryService.exportIndicatorExcel(grid, out);
			out.flush();
		} catch (IOException e){
			e.printStackTrace();
		}
		finally {
			Streams.safeClose(out);
		}
	}
	
	
	public String importIndicator(ReportIndicatorQueryVO queryVO) {
		String indicatorExcelExport = reportIndicatorQueryService.indicatorExcelExport(queryVO);
		return indicatorExcelExport;
	}
	
	private Map<String, AreaVO> listToMap(List<AreaVO> list){
		Map<String, AreaVO> tempMap = new HashMap<String, AreaVO>();
		for (AreaVO vo : list){
			tempMap.put(vo.getId(), vo);
		}
		return tempMap;
	}
}
